<template>
  <view class="auditacion">
    <form class="form" @submit="handlefn">
      <view class="form-item">
        <view class="label">
          意见留言
        </view>
        <view class="input">
          <textarea v-model="yjly" type="text" placeholder="请输入意见留言"/>
        </view>
      </view>
      <view class="form-item" v-if="isblr">
        <view class="label">
          办理人
        </view>
        <view class="input tag-box" v-if="nextData">
          <u-tag @click="toggleBLR(item)"
                 v-for="(item,index) in selectBrl"
                 :text="item.userName"
                 :key="index"
                 :mode="item.isSel? 'dark' : 'plain' "
                 shape="circle"/>
          <u-tag v-if="isSelUser" text="添加" mode="plain" @click="addTarget" shape="circle"></u-tag>
        </view>
      </view>

      <view class="form-item" v-if="imgUrl">
        <view class="label">
          电子签章
        </view>
        <view class="input ">
          <image class="dzqz" :src="imgUrl"></image>
        </view>
      </view>

      <view class="float-button" v-if="isfs">
        <view class="button-group">
          <u-button @click="handlefn" :custom-style="customButton" ripple formType="submit">发 送</u-button>
        </view>
      </view>
    </form>
  </view>
</template>

<script>
import FormItem from "../../components/form-item/form-item";
import UTag from "../../uview-ui/components/u-tag/u-tag";
import UButton from "../../uview-ui/components/u-button/u-button";
import { mapGetters } from 'vuex'
import { claerBadge, routeTo } from "../../utils/util";
const customButton = {
  color: '#FFFFFF',
  backgroundColor: '#5f8ab4',
  width:'100%',
  border: 'none',
  borderRadius:'0'
}
export default {
  components: { UButton, UTag, FormItem },
  data() {
    return {
      customButton,
      taskId: '',
      stepId: '',
      stepNo: '',
      flowId: '',
      auditId: '',
      scan: false,
      isblr: false,
      isnext: false,
      nextData: null,
      isfs: true,
      yjly: '',
      title: '',
      selectBrl: [],
      selectBrlZh: [],
      isSelUser: false,
      imgUrl: ''
    }
  },
  computed: {
    ...mapGetters([ 'taskData' ])
  },
  methods: {
    addTarget() {
      let that = this;
      console.log(that.selectBrl, "8888888")
      this.selectBrl.forEach(item => {
        if (item.isSel) {
          this.selectBrlZh.push(item.userId);
        }
      })
      routeTo({
        link: "buddyList",
        events: {
          async sendContactData(res) {
            if (res.data.length > 0) {
              let targets = [];
              that.selectBrl = [];
              res.data.forEach((user, i) => {
                that.selectBrl.push({
                  isSel: true,
                  userId: user.userId,
                  userName: user.userName
                })
              })
            }
          }
        },
        params: {
          actionType: 'addTarget',
          userIds: this.selectBrlZh.join(" ")
        }
      })
    },
    toggleBLR(blr) {
      if (this.nextData.recipient.ismulti == 1) {
        this.selectBrl.forEach((item, index) => {
          if (item.userId == blr.userId) {
            if (item.isSel == true) {
              this.selectBrl[index].isSel = false
            } else {
              this.selectBrl[index].isSel = true
            }
          }
        })
      } else {
        this.selectBrl.forEach((item, index) => {
          if (item.isSel == true) {
            this.selectBrl[index].isSel = false
          }
        })
        this.selectBrl.forEach((item, index) => {
          if (item.userId == blr.userId) {
            if (item.isSel == true) {
              this.selectBrl[index].isSel = false
            } else {
              this.selectBrl[index].isSel = true
            }
          }
        })
      }


    },
    async handlefn() {
      uni.showLoading({
        title: '保存数据',
        mask: true,
      })
      uni.showNavigationBarLoading();
      let data = await this.api.saveAudit({
        taskId: this.taskId,
        auditOption: this.auditId,
        auditValue: this.yjly
      })

      if (data.code === 0) {
        if (data.data !== "") {
          uni.showModal({
            title: '提示',
            content: data.data,
            showCancel: false,
          })
        } else {
          uni.showLoading({
            title: '发送任务中',
            mask: true,
          })
          uni.showNavigationBarLoading();
          if (!this.isnext) {
            let _data = await this.handleCheck()
            let r = JSON.parse(_data.data);
            if (r.returnType == 0) {
              //显示代办人信息
              this.nextData = r
              uni.setNavigationBarTitle({
                title: this.title + "--" + r.nextStep.stepName,
              })
            } else if (r.returnType == 1 || r.returnType == 2 || r.returnType == 3) {
              //发送 不要操作
              uni.showToast({
                title: '任务办理成功!',
                duration: 2000,
              });
              claerBadge()
              setTimeout(function () {
                uni.navigateBack({
                  delta: 2,
                })
                uni.$emit('update', { payload: '刷新待办' })
              }, 2000)
            } else if (r.returnType == 999) {
              uni.showModal({
                title: '提示',
                content: r.msg,
                showCancel: false,
              })
            }
          } else {
            this.selectBrl.forEach(item => {
              if (item.isSel) {
                this.selectBrlZh.push(item.userId);
              }
            })
            if (this.selectBrlZh.length == 0) {
              uni.hideLoading();
              uni.hideNavigationBarLoading()
              uni.showToast({
                title: '至少选择一个办理人!',
                duration: 2000,
                icon: "none"
              });
              return;
            }
            let res = await this.api.taskSend({
              flowId: this.taskData.wfModel.id,
              target: this.selectBrlZh.join(" "),
              title: this.taskData.wfTaskModel.title,
              priority: 0,
              nextStepNo: this.nextData.nextStep.stepNo,
              stepId: this.taskData.wfTaskModel.stepId,
              taskId: this.taskData.wfTaskModel.id
            })

            uni.hideLoading();
            uni.hideNavigationBarLoading();

            if (res.code === 0) {
              if (res.data == "") {
                uni.showToast({
                  title: '任务办理成功!',
                  duration: 2000,
                });
                claerBadge()
                setTimeout(function () {
                  uni.navigateBack({
                    delta: 2,
                  })
                  uni.$emit('update', { payload: '刷新待办' })
                }, 2000)
              } else {
                uni.showModal({
                  title: '失败提示',
                  content: res.data,
                  showCancel: false,
                })
              }
            } else {
              uni.showModal({
                title: '失败提示',
                content: res.data,
                showCancel: false,
              })
            }

          }
        }
      } else {
        uni.showModal({
          title: '提示',
          content: '保存审核动作异常!',
          showCancel: false,
        })
      }
    },
    async handleCheck_ck() {
      uni.showLoading({
        title: '加载数据',
        mask: true,
      })
      uni.showNavigationBarLoading()
      let data = await this.api.handleCheck_ck({
        taskId: this.taskId,
        stepId: this.stepId,
        stepNo: this.stepNo,
        flowId: this.flowId
      })

      uni.hideLoading();
      uni.hideNavigationBarLoading();
      if (data.data === '0') {
        this.isblr = true;
        this.isnext = true;
        let _data = await this.handleCheck();

        if (_data.code === 0) {
          let r = JSON.parse(_data.data);
          if (r.recipient.type == 0) {
            this.isSelUser = true;
          }
          if (r.returnType === 0) {
            //显示代办人信息
            this.nextData = r;
            let userIds = r.recipient.recipient.split(" ");
            r.recipient.names.forEach((item, index) => {
              this.selectBrl.push({
                userName: item,
                userId: userIds[index],
                isSel: ((r.recipient.isAuto == 1 && r.recipient.ismulti == 1) ? true : false)
              })
            })
            uni.setNavigationBarTitle({
              title: this.title + "--" + r.nextStep.stepName,
            })
          } else if (r.returnType === 1 || r.returnType === 2 || r.returnType === 3) {
            //发送 不要操作

          } else if (r.returnType === 999) {
            this.isfs = false
            uni.showModal({
              title: '提示',
              content: r.msg,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  uni.navigateBack({
                    delta: 1,
                  })
                }
              }
            })

          }
          if (this.scan === "true") {
            //自动办理
            this.yjly = '扫描自动办理'
            await this.handlefn()
          }
        } else {
          this.isfs = false
          uni.showModal({
            title: '提示',
            content: '未获取下个节点信息!',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                uni.navigateBack({
                  delta: 1,
                })
              } else if (res.cancel) {
              }
            }
          })
        }
      }
    },
    async handleCheck() {
      uni.showLoading({
        title: '加载数据',
        mask: true,
      })
      uni.showNavigationBarLoading()
      let data = await this.api.handleCheck({
        taskId: this.taskId,
        stepId: this.stepId,
        stepNo: this.stepNo,
        flowId: this.flowId
      })
      uni.hideLoading();
      uni.hideNavigationBarLoading();
      return data
    },
    async getSignatureImg() {
      let data = await this.api.getSignatureImg();
      if (data.data.data) {
        this.imgUrl = 'data:image/png;base64,' + data.data.data
      }
    }
  },

  onLoad(options) {
    this.taskId = options.taskId;
    this.stepId = options.stepId;
    this.stepNo = options.stepNo;
    this.flowId = options.flowId;
    this.auditId = options.auditId;
    this.scan = options.scan;
    this.title = options.t;
    this.handleCheck_ck();
    this.getSignatureImg();
  }
}
</script>

<style lang="less" scoped>
.auditacion {
  background: #f2f2f2;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding: 20rpx 0 120rpx;
  /* #ifdef H5 */
  min-height: calc(100vh - 88rpx);
  /* #endif */

  .form {
    padding: 0 0 calc(40rpx + env(safe-area-inset-bottom)) 0;

    .form-item {
      background: #FFFFFF;
      padding: 20rpx;
      margin-bottom: 20rpx;

      .label {
        .require {
          color: red;
          margin-right: 3rpx;
        }
      }

      .input {
        margin-top: 20rpx;

        textarea {
          width: 100%;
        }
      }

      .tag-box {
        display: flex;
        flex-wrap: wrap;

        .u-tag {
          margin: 20rpx 20rpx 0 0;
          transition: background ease-in-out .2s;

          &.select {
            background: #2979ff;
            color: #FFF;
          }
        }
      }

    }

    .float-button {
      position: fixed;
      width: 100%;
      background-color: #FFF;
      padding: 0 0   env(safe-area-inset-bottom) 0;
      bottom: 0;
      display: flex;
      z-index: 1;
      align-items: center;

      .button-group {
        display: flex;
        justify-content: center;
        flex: 1;
        align-content: center;
        :nth-child(2){
          margin: 0 0 0 20rpx;
        }
        u-button{
          flex: 1;
          display: block;
        }
      }
      .more-btton {
        display: flex;
        color: #333;
        flex-direction: column;
        margin-right: 20rpx;
        align-items: center;
        justify-content: center;

        .icon-gengduo {
          font-size: 36rpx;
          margin-bottom: 5rpx;
        }

        .text {
          font-size: 20rpx;
        }
      }

    }
  }

  .dzqz {
    width: 100%;
    height: 500rpx;
  }
}
</style>
